<!DOCTYPE html>
<html>
  <head>
    <!-- Update title -->
    <title>Flocking: Part 2</title>

    <!-- keywords used for searching -->
    <meta name="keywords" content="guide, flocking, particles">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- reference to Cinder classes -->
      <!-- <ci seealso dox="[CLASS NAME GOES HERE]" label="[NAME OF LINK]"></ci> -->

      <!-- master stylesheet - these links will be replaced when compiled -->
    <link rel="stylesheet" href="../../_assets/css/foundation.css">
    <link rel="stylesheet" href="../../_assets/css/prism.css">
    <link rel="stylesheet" href="../../_assets/css/style.css">
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700' rel='stylesheet' type='text/css'>

    <!-- Place additional stylsheet links here, which will be copied over when compiled (optional) -->
    
  </head>

  <body id="guide-contents" class="language-c++">

    <!-- CONTENT STARTS HERE -->
    <h1><a class="anchor" id="sectionName"></a>
    RULE 1: SEPARATION (Avoid crowding)</h1>
    <p><br />
    <br />
    </p><div class="image">
    <img src="images/rule1.jpg" alt="rule1.jpg"/>
    </div>
    <p> <br />
     <br />
    The first rule of flocking is that objects want their own space. They will do what they can to avoid overcrowding. If two objects are moving towards each other, the closer they get, the more they are compelled to adjust their velocity so that they begin to move away from each other. Since we are building on the work of <a href="http://www.red3d.com/cwr/boids/">Reynolds</a>, we are going to use his naming conventions for the forces that act on flocking objections. The <em>repulsion</em> force from <a class="el" href="hello_cinder_chapter5.html">Hello, Cinder: Section 1, Chapter 5</a> will now be called a <em>separation</em> force. <br />
     <br />
     
    <div class="fragment"><pre class="fragment"><span style="font-size: small;">void ParticleController::applyForce( float zoneRadiusSqrd )
    {
      for( list::iterator p1 = mParticles.begin(); p1 != mParticles.end(); ++p1 ) {

        list::iterator p2 = p1;
        for( ++p2; p2 != mParticles.end(); ++p2 ) {
          Vec3f dir = p1-&gt;mPos - p2-&gt;mPos;
          float distSqrd = dir.lengthSquared();

          if( distSqrd &lt;= zoneRadiusSqrd ) { // SEPARATION
            <span style="color: #3366ff;">float F = ( zoneRadiusSqrd/distSqrd - 1.0f ) * 0.01f;
            dir = dir.normalized() * F;
            p1-&gt;mAcc += dir;
            p2-&gt;mAcc -= dir;</span>
          }
        }
      }
    }</span></pre></div>
    </p>
    <p><br />
    We use two nested list iterators to compare each Particle with every other Particle. As you can imagine, this slows down dramatically as the number of Particles increases. For the purpose of this tutorial, we are going to use 500 Particles. Every one of these 500 Particles will compare its position to the position of the other 499 Particles. The distance between these objects is noted and if the distance is less than our defined threshold, then apply the separation force. <br />
     <br />
    Finding the square-root of a number is computationally heavy, and it's necessary to find the distance between two points. But there's a simple optimization we can make here because we don't actually need the true distance between the two particles. We just want to see if their distance is less than the zoneRadius. Consider this: if A &lt; B then A^2 &lt; B^2. So if distance &lt; zoneRadius, then distance^2 &lt; zoneRadius ^ 2. And distance^2 is much faster to compute, since it doesn't involve a sqrt() which is <a href="http://en.wikipedia.org/wiki/Methods_of_computing_square_roots">notoriously processor intensive</a>. So we will use lengthSquared() instead of length(). <br />
     <br />
    To clarify further, to find the length of the vector between two points, we would solve <em>sqrt( x*x + y*y + z*z )</em>. If we want to find out the square of the length of the same vector, we would just need to solve <em>x*x + y*y + z*z</em>. By using lengthSquared(), we are saving ourselves 124,750 <em>sqrt()</em> calls per frame. <br />
     <br />
    The <em>F </em>(force) variable represents the strength of the force acting on the Particles. This variable is definitely up for personal interpretation. For example, if we were simulating the repulsion between two hydrogen atoms, we would know what the force would be because it is something that can be derived mathematically (mostly). However, the force acting between two flocking objects like birds or fish is not something that can yet, if ever, be measured.<em> (When I start messing around with flocking simulations, I spend a great deal of time fine tuning this <em>F</em> number. Really tiny changes can create a stunning number of different behaviors.)</em> So when we say . . . <br />
     <br />
    </p><div class="fragment"><div class="line"><span class="keywordtype">float</span> F = ( zoneRadiusSqrd/distSqrd - 1.0f ) * 0.01f;</div>
    </div><!-- fragment --><p><br />
    . . . it isn't because we are privy to some cosmic equations or laws. It is all guesswork and a lot of trial and error. In our case, we want the strength of the force to be a fraction of the inverse square of their distance from each other. The <em>0.01f</em> was chosen simply because <em>0.1f</em> was way too strong and <em>0.001f</em> was way too weak. The image below shows an approximation of how the force changes in relation to the distance between the particles. <br />
     <br />
    </p><div class="image">
    <img src="images/curve1.jpg" alt="curve1.jpg"/>
    </div>
    <p> <br />
     <br />
    The next line takes the result of our force equation and uses it to scale a normalized vector. <br />
     <br />
    </p><div class="fragment"><div class="line">dir = dir.normalized() * F;</div>
    </div><!-- fragment --><p><br />
    Remember, a normalized vector is a vector that has a length of 1.0. Before this equation, <em>dir</em> represents a vector pointing from p1's position to p2's position. Since we are interested in the direction but not the distance, we normalize the vector. Then we multiply this normalized vector by the result of our force equation and we end up with a vector we can use to influence the movement of both Particles. <br />
     </p>
    <h1><a class="anchor" id="sectionName"></a>
    RULE 1: SEPARATION (Avoid crowding)</h1>
    <p><br />
    Because we are dealing with a <a href="http://en.wikipedia.org/wiki/Euler_method">Euler approach</a> to particles (as opposed to the more accurate but more complex <a href="http://en.wikipedia.org/wiki/Verlet_integration">Verlet</a> or <a href="http://en.wikipedia.org/wiki/Runge-kutta">Runge-Kutta</a>), we need to find a way to deal with the eventuality that two particles will end up being too close to each other and therefore be subject to massive repulsive forces which would send them flying offscreen. We do this by way of a speed limit. If the particle ever goes faster than our max speed, we find the velocity direction and multiply it by the speed limit and use this new velocity instead. Note that we are comparing the square of the distance in order to save us an undesirable <em>sqrt()</em>. <br />
     <br />
    </p><div class="fragment"><div class="line"><span class="keywordtype">float</span> velLengthSqrd = mVel.lengthSquared();</div>
    <div class="line"><span class="keywordflow">if</span>( velLengthSqrd &gt; mMaxSpeedSqrd ) {</div>
    <div class="line">  mVel.normalize();</div>
    <div class="line">  mVel *= mMaxSpeed;</div>
    <div class="line">}...</div>
    </div><!-- fragment --><p><br />
    We can also use this method to prevent our Particles from ever reaching equilibrium. We never really want all the Particles to settle into a position permanently. It might be a desirable effect for other types of simulation, but for ours we always want our Particles to be in motion. Therefore, we impose a minimum speed limit as well. <br />
     <br />
    </p><div class="fragment"><div class="line">... <span class="keywordflow">else</span> <span class="keywordflow">if</span>( velLengthSqrd &lt; mMinSpeedSqrd ) {</div>
    <div class="line">  mVel.normalize();</div>
    <div class="line">  mVel *= mMinSpeed;</div>
    <div class="line">}</div>
    </div><!-- fragment --><p><br />
    If you run the app, you will see something like this: <br />
     <br />
    </p><div class="image">
    <img src="images/chapter2.jpg" alt="chapter2.jpg"/>
    </div>
    <p> <br />
     <br />
    Try adjusting the size of the zone radius to see how it affects the behavior of the Particles. A really small zone leads to the global gravitational force taking over and the Particles congregate near the center of the screen. But as you increase the zone radius, the Particles begin to spread out and the effect of the repulsion becomes apparent. <br />
     <br />
    That concludes Chapter 2. Next, in <a class="el" href="chapter3.html">Flocking Chapter 3</a>, we will be adding our second rule of flocking: cohesion. <br />
    </p>
    <!-- END CONTENT -->

    <!-- Scripts -->
    <script src="../../_assets/js/prism.js" type="text/javascript"></script>
    <!-- Place additional scripts here (optional) -->
    <!-- <script type="text/javascript"></script> -->

  </body>
</html> 